﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BC;
using BE;
using DAL;
using Microsoft.ApplicationBlocks.Data;
namespace ModuleDuoc.DM
{
    public partial class DM_DM_THUOC : ModuleDuoc.Base.frmAddBase
    {
        DataTable dt;
        int _err;
        public DM_DM_THUOC()
        {
            InitializeComponent();
        }
        #region load form

        private void DM_DM_THUOC_Load(object sender, EventArgs e)
        {
            dgvData.AutoGenerateColumns = false;
            getThuoc();
            getDVT();
            getNhomThuoc();
            getNSX();
            //this.cboxViTri.Text = "1";
            fillCboxViTri();
            cboxNhietDo.Text = "Bảo quản ở nhiệt độ phòng";
            //this.txtMaThuoc.Text = getMaThuoc_Max();
        }
        private void fillCboxViTri()
        {
            Zd_ViTriBC bcViTri = new Zd_ViTriBC();
            DataTable dt1 = new DataTable();
            dt = bcViTri.GetAll();
            cboxViTri.DataSource = dt;
            cboxViTri.DisplayMember = "TenViTri";
            cboxViTri.ValueMember = "TenViTri"; 
        }

        private string getMaThuoc_Max()
        {
            string sql = "SELECT isnull(max(CONVERT(INT, mavt)) + 1,0) FROM zD_DM_THUOC";
            
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            return dt.Rows[0][0].ToString();
        }

        private void getThuoc()
        {
            BC.ZD_DM_THUOCBC bc = new ZD_DM_THUOCBC();
            dt = new DataTable();
            dt = bc.GetAll();
            this.dgvData.DataSource = dt;
        }

        private void getDVT()
        {
            string sql = "SELECT * FROM zD_DM_DVT ORDER BY Ten";
            dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboxDVT.DataSource = dt;
            this.cboxDVT.DisplayMember = "Ten";
            this.cboxDVT.ValueMember = "Ma";
        }

        private void getNhomThuoc()
        {
            string sql = "SELECT * FROM zD_DM_VATTU_NHOMVATTU ORDER BY TENNHOM";
            dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboxNhomThuoc.DataSource = dt;
            this.cboxNhomThuoc.DisplayMember = "TenNhom";
            this.cboxNhomThuoc.ValueMember = "MaNhom";
        }

        private void getNSX()
        {
            string sql = "SELECT * FROM zD_Duoc_NSX ORDER BY TenNSX";
            dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            this.cboxNSX.DataSource = dt;
            this.cboxNSX.DisplayMember = "TenNSX";
            this.cboxNSX.ValueMember = "TenNSX";
        }

        #endregion
        
        #region check input

        private void setTab(Control c, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                c.Focus();
            }
        }

        private void txtMaThuoc_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtTonToiDa_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private void txtTonToiThieu_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), "[0123456789]") && !Char.IsControl(e.KeyChar))
                e.Handled = true;
        }

        private bool checkMaHangHoa()
        {
            string sql = "SELECT * FROM zD_DM_THUOC zdt WHERE zdt.MAHANGHOA = '" + this.txtMaThuoc.Text + "'";
            dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (dt.Rows.Count > 0)
            {
                MessageBox.Show("Trùng mã hàng hóa!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtMaThuoc.Focus();
                return false;
            }
                    
            return true;
        }

        private bool checkInput()
        {
            if (this.txtMaThuoc.Text == "")
            {
                MessageBox.Show("Mã thuốc không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtMaThuoc.Focus();
                return false;
            }
            else if (this.txtTenThuoc.Text == "")
            {
                MessageBox.Show("Tên thuốc không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtTenThuoc.Focus();
                return false;
            }
            else if (this.cboxNhomThuoc.Text == "")
            {
                MessageBox.Show("Nhóm thuốc không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.cboxNhomThuoc.Focus();
                return false;
            }
            else if (this.cboxDVT.Text == "")
            {
                MessageBox.Show("Đơn vị tính không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.cboxDVT.Focus();
                return false;
            }
            else if (this.txtDG1.Text == "")
            {
                MessageBox.Show("Thuộc tính đóng gói không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtDG1.Focus();
                return false;
            }
            else if (this.txtTonToiDa.Text == "")
            {
                MessageBox.Show("Tồn tối đa không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtTonToiDa.Focus();
                return false;
            }
            else if (this.txtTonToiThieu.Text == "")
            {
                MessageBox.Show("Tồn tối thiểu không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtTonToiThieu.Focus();
                return false;
            }
            else if (this.txtSuDung.Text == "")
            {
                MessageBox.Show("Cách sử dụng/liều dùng không hợp lệ!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.txtSuDung.Focus();
                return false;
            }
            return true;
        }
        #endregion

        #region Key Down
        private void txtMaThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtTenThuoc, e);
            }
        }

        private void txtTenThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtHoatChat, e);
            }
        }

        private void cboxNhomThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.cboxDVT, e);
            }
        }

        private void cboxDVT_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.cboxViTri, e);
            }
        }

        private void txtTTDG_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtDG2, e);
            }
        }

        private void txtTonToiDa_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtTonToiThieu, e);
            }
        }

        private void txtTonToiThieu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtSuDung, e);
            }
        }

        private void txtHoatChat_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.cboxNhomThuoc, e);
            }
        }

        private void txtHoatChat_TextChanged(object sender, EventArgs e)
        {
            this.txtTimKiem.Text = (this.txtTenThuoc.Text + " (" + this.txtHoatChat.Text + ")");
        }
        #endregion

        #region btn event

        public override void btnSave_Click(object sender, EventArgs e)
        {
            base.btnSave_Click(sender, e);
            insert();
        }

        public override void btnThemMoi_Click(object sender, EventArgs e)
        {
            base.btnThemMoi_Click(sender, e);
            this.clearField();
        }

        private void insert()
        {
            try
            {
                if (checkInput() == true)
                {
                    ZD_DM_THUOC be = new ZD_DM_THUOC();
                    ZD_DM_THUOCBC bc = new ZD_DM_THUOCBC();
                    if (this.txtMaVT.Text == "")
                    {
                        be.MAVT = getMaThuoc_Max();
                    }
                    else
                    {
                        be.MAVT = this.txtMaVT.Text;
                    }
                    be.MAHANGHOA = this.txtMaThuoc.Text;
                    be.TENVT = this.txtTenThuoc.Text.Trim();
                    be.MANHOMVATTU = this.cboxNhomThuoc.SelectedValue.ToString();
                    be.DVT = Int32.Parse(this.cboxDVT.SelectedValue.ToString());
                    be.THUOCTINHDONGGOI = this.txtDG1.Text;
                    be.MANSX = "XX";
                    be.TONTOIDA = Double.Parse(this.txtTonToiDa.Text);
                    be.TONTOITHIEU = Double.Parse(this.txtTonToiThieu.Text);
                    be.VITRILUUTRU = this.cboxViTri.Text;
                    be.CHINHANH_DB = "100";
                    be.NHACC = "Nhà cc";
                    be.Infoinclude = this.txtHoatChat.Text.Trim();
                    be.Usage = this.txtSuDung.Text;
                    be.NameSearch = (this.txtTenThuoc.Text.Trim() + " (" + this.txtHoatChat.Text + ")").Replace(" ", "").Trim();
                    be.NhietDo = cboxNhietDo.Text;
                    be.TenNSX = cboxNSX.Text;
                    be.Field1 = txtTacDungPhu.Text;
                    be.Field2 = txtTuongTacThuoc.Text;
                    be.Field3 = "";

                    if (this.chkAnhSang.Checked == true)
                    {
                        be.AnhSang = 1;
                    }
                    else
                    {
                        be.AnhSang = 0;
                    } 
                    if (this.chkTamTay.Checked == true)
                    {
                        be.TamTay = 1;
                    }
                    else
                    {
                        be.TamTay = 0;
                    }
                    if (this.chkAmUot.Checked == true)
                    {
                        be.AmUot = 1;
                    }
                    else
                    {
                        be.AmUot = 0;
                    }
                    if (this.chkHuongThan.Checked == true)
                    {
                        be.HuongThan = 1;
                    }
                    else
                    {
                        be.HuongThan = 0;
                    }
                    if (this.chkBanTheoDon.Checked == true)
                    {
                        be.BanTheoDon = 1;
                    }
                    else
                    {
                        be.BanTheoDon = 0;
                    }

                    if (this.chkBaoHiem.Checked == true)
                        be.ThuocBH = 1;
                    else
                        be.ThuocBH = 0;

                    if (this.txtMaVT.Text == "")
                    {
                        if (checkMaHangHoa() == true)
                        {
                            bc.Insert(be);
                            MessageBox.Show("Thêm mới thành công!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            this.clearField();
                        }
                        else
                        {
                            MessageBox.Show("Trùng mã hàng hóa!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            this.txtMaThuoc.Focus();
                        }
                    }
                    else
                    {
                        bc.Update(be);
                        MessageBox.Show("Cập nhật thành công!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.clearField();
                    }
                    this.txtMaThuoc.Focus();
                    getThuoc();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void clearField()
        {
            this.txtMaThuoc.Text = "";
            this.txtTenThuoc.Text = "";
            this.txtHoatChat.Text = "";
            this.txtSuDung.Text = "";
            this.txtTimKiem.Text = "";
            this.txtDG1.Text = "1x1";
            this.txtTonToiDa.Text = "0";
            this.txtTonToiThieu.Text = "0";
            this.txtMaVT.Text = "";
            this.txtTuongTacThuoc.Text = "";
            this.txtTacDungPhu.Text = "";
        }

        #endregion

        private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            clickCell();
        }

        private void clickCell()
        {
            this.clearField();
            this.txtMaThuoc.Text = this.dgvData.CurrentRow.Cells["mahanghoa"].Value.ToString();
            this.txtTenThuoc.Text = this.dgvData.CurrentRow.Cells["tenvt"].Value.ToString();
            this.cboxNhomThuoc.SelectedValue = this.dgvData.CurrentRow.Cells["manhomvattu"].Value.ToString();
            this.cboxDVT.SelectedValue = this.dgvData.CurrentRow.Cells["dvt"].Value.ToString();
            this.txtDG1.Text = this.dgvData.CurrentRow.Cells["thuoctinhdonggoi"].Value.ToString();
            this.txtTonToiDa.Text = this.dgvData.CurrentRow.Cells["tontoida"].Value.ToString();
            this.txtTonToiThieu.Text = this.dgvData.CurrentRow.Cells["tontoithieu"].Value.ToString();
            this.txtHoatChat.Text = this.dgvData.CurrentRow.Cells["Infoinclude"].Value.ToString();
            this.txtSuDung.Text = this.dgvData.CurrentRow.Cells["Usage"].Value.ToString();
            this.txtMaVT.Text = this.dgvData.CurrentRow.Cells["mavt"].Value.ToString();
            this.cboxNhietDo.Text = this.dgvData.CurrentRow.Cells["NhietDo"].Value.ToString();
            this.cboxViTri.Text = this.dgvData.CurrentRow.Cells["vitriluutru"].Value.ToString();
            this.txtTacDungPhu.Text = this.dgvData.CurrentRow.Cells["Field1"].Value.ToString();
            this.txtTuongTacThuoc.Text = this.dgvData.CurrentRow.Cells["Field2"].Value.ToString();
            try
            {
                this.cboxNSX.Text = this.dgvData.CurrentRow.Cells["TenNSX"].Value.ToString();
            }
            catch { }

            if (this.dgvData.CurrentRow.Cells["AnhSang"].Value.ToString() == "True")
            {
                this.chkAnhSang.Checked = true;
            }
            else
            {
                this.chkAnhSang.Checked = false;
            }
            if (this.dgvData.CurrentRow.Cells["TamTay"].Value.ToString() == "True")
            {
                this.chkTamTay.Checked = true;
            }
            else
            {
                this.chkTamTay.Checked = false;
            }
            if (this.dgvData.CurrentRow.Cells["AmUot"].Value.ToString() == "True")
            {
                this.chkAmUot.Checked = true;
            }
            else
            {
                this.chkAmUot.Checked = false;
            }
            if (this.dgvData.CurrentRow.Cells["HuongThan"].Value.ToString() == "True")
            {
                this.chkHuongThan.Checked = true;
            }
            else
            {
                this.chkHuongThan.Checked = false;
            }
            if (this.dgvData.CurrentRow.Cells["BanTheoDon"].Value.ToString() == "True")
            {
                this.chkBanTheoDon.Checked = true;
            }
            else
            {
                this.chkBanTheoDon.Checked = false;
            }
            //this.cboxNSX.Text = this.dgvData.Rows[this.dgvData.CurrentRow.Index].Cells["TenNSX"].Value.ToString();
            if (this.dgvData.CurrentRow.Cells["ThuocBH"].Value.ToString() == "True")
                this.chkBaoHiem.Checked = true;            
            else
                this.chkBaoHiem.Checked = false;
            
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (this.textBox1.Text != "")
                {
                    string sql = "SELECT * FROM [hien_DMThuoc-TenNhom] WHERE TENVT LIKE N'%" + this.textBox1.Text + "%'";
                    dt = new DataTable();
                    dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                    if (this.dt.Rows.Count > 0)
                    {
                        this.cboxNhomThuoc.Text = dt.Rows[0][1].ToString();
                    }
                }
            }
            catch (Exception)
            { }
        }

        private void cboxNhomThuoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                string sql = "SELECT * FROM [hien_DMThuoc-TenNhom] WHERE tennhom = N'" +this.cboxNhomThuoc.Text.ToString()+ "'";
                dt = new DataTable();
                dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                if (this.dt.Rows.Count > 0)
                {
                    this.dataGridView1.DataSource = dt;
                    this.label15.Text = dt.Rows.Count.ToString();
                }
            }
            catch (Exception)
            { }
        }

        private void btnThemNhom_Click(object sender, EventArgs e)
        {
            DM.DM_NhomThuoc f = new DM_NhomThuoc();
            f.ShowDialog();
        }

        public override void btnXoa_Click(object sender, EventArgs e)
        {
            base.btnXoa_Click(sender, e);
            if (this.txtMaVT.Text != "")
            {
                checkThuocNhapKho();
                if (_err <= 0)
                {
                    if (MessageBox.Show("Bạn có muốn hủy phiếu này không?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        string sql = "DELETE FROM zD_DM_THUOC WHERE MAVT = '" + this.txtMaVT.Text + "'";
                        SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql);
                        MessageBox.Show("Xóa thành công!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.getThuoc();
                    }
                }
                else
                {
                    MessageBox.Show("Thuốc này đã được nhập kho nên không xóa được!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private int checkThuocNhapKho() // kiem tra xem thuoc da duoc nhap kho hay chua, neu chua nhap kho thi moi duoc xoa
        {
            _err = 0;

            string sql = "SELECT * FROM zD_PHIEUNHAPKHOCT zp WHERE zp.mavt = '"+this.txtMaVT.Text+"'";
            dt = new DataTable();
            dt = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
            if (this.dt.Rows.Count > 0)
            {
                _err++;
            }
            return _err;
        }

        private void dgvData_KeyDown(object sender, KeyEventArgs e)
        {
            clickCell();
        }

        private void dgvData_KeyUp(object sender, KeyEventArgs e)
        {
            clickCell();
        }

        private void chkTimKiem_CheckedChanged(object sender, EventArgs e)
        {
            this.getThuoc();
        }

        private void txtTenThuoc_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (this.chkTimKiem.Checked == true)
            {
                DataTable dt1 = new DataTable();
                string sql = "SELECT [ID], [MAVT], [MAHANGHOA], [TENVT], [MANHOMDV], [MANHOMVATTU], [DVT], [THUOCTINHDONGGOI], [MANSX], [TONTOIDA], [TONTOITHIEU], [VITRILUUTRU], [GHICHU], [CHINHANH_DB], [NHACC], [Infoinclude], [Usage], [NameSearch],NhietDo, AnhSang,TamTay,AmUot,HuongThan,BanTheoDon, ThuocBH FROM [dbo].[zD_DM_THUOC] WHERE [tenvt] LIKE N'%" + this.txtTenThuoc.Text + "%' ORDER BY TENVT";
                dt1 = SqlHelper.ExecuteDataset(ConfigurationManager.AppSettings["Main.ConnectionString"], CommandType.Text, sql).Tables[0];
                this.dgvData.DataSource = dt1;
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            frmViTri f = new frmViTri();
            f.ShowDialog();
        }

        private void chkTimKiem_CheckedChanged_1(object sender, EventArgs e)
        {
            if (chkTimKiem.Checked == false)
            {
                getThuoc();
            }
        }

        private void cboxViTri_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtDG1, e);
            }
        }

        private void txtDG2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtDG3, e);
            }
        }

        private void txtDG3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtTonToiDa, e);
            }
        }

        private void txtSuDung_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtTacDungPhu, e);
            }
        }

        private void txtTacDungPhu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.txtTuongTacThuoc, e);
            }
        }

        private void txtTuongTacThuoc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                setTab(this.cboxNhietDo, e);
            }
        }
    }
}

